package com.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dao.UserDao;
import com.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

public class UserRealm extends AuthorizingRealm {
    @Resource
    private UserDao userDao;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权处理！！！");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermission("user:add");
//        simpleAuthorizationInfo.addStringPermission ( "user:del" );
        simpleAuthorizationInfo.addRole("admin");
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证处理！！！");

        String username = (String)authenticationToken.getPrincipal();
        //查询条件
        QueryWrapper<User> wrapper = new QueryWrapper<com.pojo.User>();
        wrapper.eq("name",username);

        //查询用户
        com.pojo.User user = userDao.selectOne(wrapper);
        if (user == null){
            throw new AuthenticationException("用户名不存在");
        }else {
            // 获取当前Shiro中存在的已经登录构建的Subject对象
            UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
            // 获取数据库中用户进行比对
            if ( ! user.getName().equals ( usernamePasswordToken.getUsername () ) ){
                return 	null;
            }
            // 密码比对Shiro无需外部验证，由Shiro自己完成
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo( usernamePasswordToken, user.getPassword(), getName () );

            return simpleAuthenticationInfo;
        }
    }
}
